package com.ajouroid.smartcoworker;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;

import android.util.Log;

public class HttpConnector {

	public static String ip = "210.107.197.196";
	
	/*
	public static void setAddress(String _addr)
	{
		ip = _addr;
	}
	*/
	
	public static String getProfileImageUrl(String img)
	{
		if(img == null){
			return null;
		}
		
		String url = getAddress() + "profile/" + img;
		
		return url;
	}
	
	public static String getAddress()
	{
		return "http://" + ip + "/PresentationServer/";
	}
	
	/** Post to web server
	 * 
	 * @param action : Servlet name
	 * @param msgs : HashMap of Parameters
	 * @return Response string
	 */
	public String post(String action, Map<String,String> msgs)
	{
		String urlStr = getAddress() + action;
		
		HttpClient httpClient = null;
		try {
			httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
	
	
			HttpPost httpPost = new HttpPost(urlStr);
			httpPost.setHeader("Content-Disposition","form-data");
			
			List<NameValuePair> pair = new ArrayList<NameValuePair>();
			
			Iterator<String> itr = msgs.keySet().iterator();
			
			// put parameters into entity
			while (itr.hasNext())
			{
				String key = itr.next();
				String value = msgs.get(key);
				pair.add(new BasicNameValuePair(key, value));
			}
	
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pair, "UTF-8");
			
			httpPost.setEntity(entity);
						
			HttpResponse response = httpClient.execute(httpPost);
			
			String respStr = getResponseText(response);
			
			return respStr;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null)
				httpClient.getConnectionManager().shutdown();
		}
		
		return null;
	}
	
	/** Get from web server
	 * 
	 * @param action : Servlet name
	 * @param msgs : HashMap of Parameters
	 * @return Response string
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public String get(String action, Map<String,String> msgs) throws ClientProtocolException, IOException
	{
		String urlStr = getAddress() + action;
		
		String query = "?";
		
		Set<Entry<String,String>> entrySet = msgs.entrySet();
		
		Iterator<Entry<String, String>> itr = entrySet.iterator();
		Entry<String, String> entry;
		
		// put parameters into url
		while (itr.hasNext())
		{
			entry = (Entry<String, String>) itr.next();
					
			String key = entry.getKey();
			String value = entry.getValue();
			
			query += String.format("%s=%s&", key, value);
		}
		
		query = query.substring(0, query.length()-1);

		urlStr += query;
		
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet get = new HttpGet(urlStr);
			HttpResponse response = httpClient.execute(get);
			
			String respStr = getResponseText(response);
			
			return respStr;
	}
	
	/** Register new user
	 * 
	 * @param id
	 * @param password
	 * @param name
	 * @param email
	 * @param image : profile image's path
	 * @return Response string
	 */
	public String register(String id, String password, String name, String email, String image)
	{
		String url = getAddress() + "Register";
		HttpClient httpClient = null;
		try {
			httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
	
	
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Disposition","form-data");
			
						
			MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			entity.addPart("id", new StringBody(id, Charset.forName("UTF-8")));
			entity.addPart("password", new StringBody(password, Charset.forName("UTF-8")));
			entity.addPart("name", new StringBody(name, Charset.forName("UTF-8")));
			entity.addPart("email", new StringBody(email, Charset.forName("UTF-8")));

			if (image != null)
			{
				File file = new File(image);
				entity.addPart("file1", new FileBody(file,"image/jpeg"));
			}
			else
			{
				
			}

			httpPost.setEntity(entity);
						
			HttpResponse response = httpClient.execute(httpPost);
			
			String respStr = getResponseText(response);
			
			return respStr;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null)
				httpClient.getConnectionManager().shutdown();
		}
		
		return null;
	}
	
	/** Create team with presentation file
	 * 
	 * @param leader
	 * @param members
	 * @param filePath : File path of presentation file
	 * @return Response string
	 */
	public String createTeam(String leader, String type, ArrayList<String> members, String filePath)
	{
		String url = getAddress() + "TeamAction";
		HttpClient httpClient = null;
		try {
			httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
	
	
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Disposition","form-data");
						
			MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			
			entity.addPart("leader", new StringBody(leader));
			entity.addPart("type", new StringBody(type));
			
			String memberStr = "";
			
			for (int i=0; i<members.size(); i++)
				memberStr += members.get(i) + ";";
			
			entity.addPart("members", new StringBody(memberStr));
			// 파일 추가...
			File file = new File(filePath);
			entity.addPart("file1", new FileBody(file,"image/jpeg"));
								
			httpPost.setEntity(entity);
						
			HttpResponse response = httpClient.execute(httpPost);
			
			String respStr = getResponseText(response);
			
			return respStr;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null)
				httpClient.getConnectionManager().shutdown();
		}
		
		return null;
	}
	
	public String getResponseText(HttpResponse response) throws IllegalStateException, IOException
	{
		HttpEntity respEntity = response.getEntity();
		
		InputStreamReader risr = new InputStreamReader(respEntity.getContent());
		BufferedReader br = new BufferedReader(risr);
		
		String line;
		StringBuffer resp=new StringBuffer();
		
		while ((line = br.readLine()) != null)
		{
			resp.append(line).append("\n");
		}
		return resp.toString();
	}
}
